<template>
  <div class="article-list">
    <van-pull-refresh 
    v-model="isLoading" 
    :success-text="successText" 
    success-duration="1500"
    @refresh="onRefresh">
    <van-list
      v-model="loading"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
    <article-item :article="article" v-for="(article,index) in list" :key="index"></article-item>
      <!-- <van-cell v-for="(article,index) in list" :key="index" :title="article.title" /> -->
    </van-list>
  </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article"
import ArticleItem from "@/components/article-item"
export default {
  name: "ArticleList",
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true,
    }
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      // timestamp:null
      page: 1,
      error: false,
      isLoading: false,
      successText:''
      }
  },
  methods: {
   async onLoad() {
      // 异步更新数据
      try {
        // 1.请求获取数据
        // 2.把请求结果放到list中
        const { data } = await getArticles({
          channel_id: this.channel.id,
          // timestamp:this.timestamp ||Date.now(),
          page: this.page || 1

        })
        // console.log(data);
        
        const { results } = data.data
        // 和之前有的数据合并，所以是push
        this.list.push(...results)
        // 3.加载状态结束
        this.loading = false;

        // 4.数据全部加载完成
        if (results.length) {
          // this.timestamp = data.data.pre_timestamp
          this.page+=1
          
        } else {
          this.finished = true;
        }
      } catch (err) {
        // console.log('请求失败',err);
        this.error = true;
        // 把加载中的提示关闭
        this.loading = false;
      }
    },
    // 下拉刷新 数据更新在最上方
    async onRefresh() {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          // 每次请求新的数据都增加一页
          page: this.page++ 
        })
        const {results} = data.data
        this.list.unshift(...results)
        // 刷新成功提示
        this.successText = `刷新成功，更新了${results.length}条数据`
        this.isLoading = false;
       } catch (err) {
        console.log('加载失败', err);
        // 加载失败提示文本
        this.isLoading = false;
        this.successText = '刷新失败'
      }
    }
  
    }
  }
</script>
<style lang="less" scoped>
.article-list{
  //给文章列表设置滚动容器
  height: 80vh;
  // 溢出滚动 垂直方向
  overflow-y: auto;
}
</style>
